package breeze.pixel.weather.error_view.service;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;

import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;

import breeze.pixel.weather.apps_util.utils.AppToolUtil;
import breeze.pixel.weather.error_view.view.ErrorView;
import brz.breeze.tool_utils.Blog;

public class ErrorCatchService implements Thread.UncaughtExceptionHandler {

    @SuppressLint("StaticFieldLeak")
    private static ErrorCatchService service;

    @SuppressLint("StaticFieldLeak")
    private static Context mContext;

    public ErrorCatchService(Context context) {
        mContext = context;
    }

    public static ErrorCatchService getInstance(Context context) {
        if (service == null) service = new ErrorCatchService(context);
        return service;
    }

    /**
     * @author BREEZE
     * @description 崩溃日志
     */
    @Override
    public void uncaughtException(Thread p1, Throwable p2) {
        try {
            Writer writer = new StringWriter();
            PrintWriter printWriter = new PrintWriter(writer);
            p2.printStackTrace(printWriter);
            Throwable tr = p2.getCause();
            while (tr != null) {
                tr.printStackTrace(printWriter);
                tr = tr.getCause();
            }
            String exception = writer.toString();
            StringReader stringReader = new StringReader(exception);
            BufferedReader bufferedReader = new BufferedReader(stringReader);
            String line = "";
            StringBuilder stringBuilder = new StringBuilder();
            while ((line = bufferedReader.readLine()) != null) {
            	if (line.contains("breeze.pixel.weather") || line.contains("java.lang")){
            		stringBuilder.append(line).append("\n");
				}
            }
            //写出错误到文件
            String filePath = AppToolUtil.getCacheFile(mContext, AppToolUtil._PATH_EXCEPTION_DIR) + "Exception.txt";
            AppToolUtil.writeDataIntoFile(exception, filePath);
            printWriter.close();
            Intent intent = new Intent(mContext, ErrorView.class);
            intent.putExtra("error", stringBuilder.toString());
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mContext.startActivity(intent);
            System.exit(0);
        } catch (Exception e) {
            Blog.e("ErrorCatchService", e.toString());
        }
    }
}
